package myky.com.doctorapp.utils.OkHttpUtils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.orhanobut.logger.Logger;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import myky.com.doctorapp.utils.LogInterceptor;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created on 2016/6/30.
 */
public class OkHttpManager {

    public static Context context;
    public static OkHttpManager serverTask;
    private static OkHttpClient okHttpClient;
    private static final int RESULT_ERROR = 1000;
    private static final int RESULT_SUCCESS = 2000;
    private HttpCallBack httpCallBack;
    private boolean NotHtml = true;
    private Request requests;
    private static HashMap<String, CallBackBean> hashMap = new HashMap<>();
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int resultCode = msg.what;
            switch (resultCode) {
                case RESULT_ERROR:
                    Bundle bundle1 = msg.getData();
                    String thread1 = bundle1.getString("ThreadName");
                    httpCallBack = hashMap.get(thread1).getHttpCallBack();
                    httpCallBack.onFailure("网络异常,请查看网络");
                    break;
                case RESULT_SUCCESS:
                    long type = 0;
                    String location;
                    String thread;
                    String result = null;
                    try {
                        Bundle bundle = msg.getData();
                        result = bundle.getString("JsonResult");
                        //重定向Location
                        location = bundle.getString("Location");
                        thread = bundle.getString("ThreadName");
                        httpCallBack = hashMap.get(thread).getHttpCallBack();
                        JSONObject jsonObject = null;
                        jsonObject = new JSONObject(result);
                        if (jsonObject.has("type")) {
                            type = jsonObject.getLong("type");
                        } else if (jsonObject.has("code")) {
                            type = jsonObject.getLong("code");
                        }
                    } catch (JSONException e) {
                        //判断是否是获取html字符串文件
                        if (NotHtml) {
                            httpCallBack.onFailure("服务异常，请稍后再试");
                            break;
                        } else {
                            httpCallBack.onResponse(result, type);
                            NotHtml = true;
                        }
                        break;
                    }
                    httpCallBack.onResponse(result, type);
                    break;
                default:
                    break;
            }


        }
    };


    public OkHttpManager() {

        if (okHttpClient == null) {
            synchronized (OkHttpManager.class) {
                if (okHttpClient == null) {
                    okHttpClient = new OkHttpClient.Builder()
                            .addInterceptor(new LogInterceptor(false))
                            .build();
                }
            }
        }
    }

    public static OkHttpManager getInstance(Context context) {

        if (serverTask == null) {
            synchronized (OkHttpManager.class) {
                if (serverTask == null) {
                    serverTask = new OkHttpManager();
                }
            }
        }
        return serverTask;
    }

    //get请求
    public void get(String url, HttpCallBack httpCallBack) {
        NotHtml = true;
        Request request = new Request.Builder()
                .url(url)
                .build();
        startRequest(request, httpCallBack);

    }

    private void startRequest(Request request, final HttpCallBack httpCallBacks) {

        final String threadName = httpCallBacks.toString();
        hashMap.put(threadName, new CallBackBean(httpCallBacks, request));
        requests = request;

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {


                Message message = handler.obtainMessage();
                message.what = RESULT_ERROR;
                message.obj = e.toString();
                Bundle bundle = new Bundle();
                //将返回的结果和respone中Location通过bundle传出去
                bundle.putString("ThreadName", threadName);
                message.setData(bundle);
                message.sendToTarget();
            }

            @Override


            public void onResponse(Call call, Response response) {
                try {
                    Message message = handler.obtainMessage();
                    Bundle bundle = new Bundle();
                    //将返回的结果和respone中Location通过bundle传出去
                    bundle.putString("ThreadName", threadName);
                    bundle.putString("JsonResult", response.body().string());
                    bundle.putString("Location", response.request().url().toString()); //重定向Location
                    message.what = RESULT_SUCCESS;
                    message.setData(bundle);
                    message.sendToTarget();
                } catch (Exception e) {
                }

            }
        });
    }

    public interface HttpCallBack {

        void onFailure(String errorMsg);

        void onResponse(String jsonObject, long type);

    }


}
